﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.Common.ExceptionHandler
{
    /// <summary>
    /// 框架自定义统一异常处理中间件
    /// </summary>
    public class FrameWorkExceptionMiddleWare
    {
        private readonly RequestDelegate _next;

        public FrameWorkExceptionMiddleWare(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await this._next.Invoke(httpContext);
            }
            catch (Exception ex)
            {
                await this.HandleExceptionAsync(httpContext, ex.Message);
            }
        }

        private async Task HandleExceptionAsync(HttpContext httpContext,string exceptionMessage)
        {
            httpContext.Response.ContentType = "application/json;charset=utf-8";

            // 1、异常结果格式处理
            dynamic warpResult = new ExpandoObject();
            
            warpResult.Success = "false";
            
            warpResult.ErrorInfo = exceptionMessage;

            var stream = httpContext.Response.Body;

            await JsonSerializer.SerializeAsync(stream, warpResult);

        }
    }
}
